/*
 ============================================================================
 Name		: CAutoTimer.cpp
 Author	  : 
 Version	 : 1.0
 Copyright   : Your copyright notice
 Description : CAutoTimer implementation
 ============================================================================
 */

#include "CAutoTimer.h"
#include "autotesterengine.h"
#include "mtalog.h"

CAutoTimer::CAutoTimer() : CActive(EPriorityStandard), iIndex(0) // Standard priority
{
}

CAutoTimer* CAutoTimer::NewLC()
{
	CAutoTimer* self = new ( ELeave ) CAutoTimer();
	CleanupStack::PushL(self);
	self->ConstructL();
	return self;
}

CAutoTimer* CAutoTimer::NewL()
{
	CAutoTimer* self = CAutoTimer::NewLC();
	CleanupStack::Pop(); // self;
	return self;
}

void CAutoTimer::ConstructL()
{
	User::LeaveIfError(iTimer.CreateLocal() ); // Initialize timer
	CActiveScheduler::Add(this); // Add to scheduler
}

CAutoTimer::~CAutoTimer()
{
	Cancel(); // Cancel any request, if outstanding
	iTimer.Close(); // Destroy the RTimer object
	// Delete instance variables if any
}

void CAutoTimer::DoCancel()
{
	iTimer.Cancel();
}

void CAutoTimer::ResetIndex()
{
	iIndex = 0;
}

void CAutoTimer::RunL()
{
	CAutoTester* autoTester = CAutoTester::GetInstance();
	bool lastKey = autoTester->SimulateKeyEvent(iIndex++);
	
	if(!lastKey)
	{
		iTimer.After(iStatus, autoTester->GetNextTimeDifference(iIndex)); 
		SetActive(); // Tell scheduler a request is active
	}
	else
	{
		LOGTXT("LAST KEY!!!!");
		autoTester->SimulateKeyEvent(iIndex); // Simulating the last key
//		autoTester->SetReplaying(EFalse); // Would be required if we don't consider key pressed while our app has focus
		CAknGlobalNote* note = CAknGlobalNote::NewL();
		CleanupStack::PushL(note);
		note->ShowNoteL(EAknGlobalInformationNote, _L("Replay Complete!"));
		CleanupStack::PopAndDestroy(1);
	}
}

void CAutoTimer::StartTimer(TInt aTimerValue)
{
	iTimer.Cancel();
	iTimer.After(iStatus, aTimerValue); 
	SetActive(); // Tell scheduler a request is active
}

TInt CAutoTimer::RunError(TInt aError)
{
	return aError;
}
